<template>
	<div ref="wrapRef" :style="{ height, width }"></div>
</template>
<script lang="ts" setup>
import { ref, nextTick, unref, onMounted, onUnmounted } from 'vue';
import { useScript } from '/@/hooks/web/useScript';
const props = defineProps({
	width: {
		type: String,
		default: '100%',
	},
	height: {
		type: String,
		default: '100%',
	},
	zoom: {
		type: Number,
		default: 5,
	},
	latitude: {
		type: Number,
		default: 101.4327,
	},
	longitude: {
		type: Number,
		default: 33.37086,
	},
});
const emits = defineEmits(['mapZoomAndCenter']);
const BAI_DU_MAP_URL = 'https://api.map.baidu.com/getscript?v=3.0&ak=kH6xgfBaXCvHElPYWbXoSIlOF8U79iyR';

const wrapRef = ref<HTMLDivElement | null>(null);
const { toPromise } = useScript({ src: BAI_DU_MAP_URL });
let map;
async function initMap() {
	await toPromise();
	await nextTick();
	const wrapEl = unref(wrapRef);
	if (!wrapEl) return;
	const BMap = (window as any).BMap;
	map = new BMap.Map(wrapEl);
	const point = new BMap.Point(props.latitude, props.longitude);
	map.centerAndZoom(point, props.zoom);
	map.enableScrollWheelZoom(true);
	map.addEventListener('dragend', handleZoomAndCenter);
	map.addEventListener('zoomend', handleZoomAndCenter);
}
function handleZoomAndCenter() {
	const center = map.getCenter();
	const zoom = map.getZoom();
	emits('mapZoomAndCenter', { center, zoom });
}
onMounted(() => {
	initMap();
});

onUnmounted(() => {
	map.removeEventListener('dragend', handleZoomAndCenter);
	map.removeEventListener('zoomend', handleZoomAndCenter);
});
</script>
<style lang="scss" scoped>
:deep(.anchorBL) {
	display: none !important;
}
</style>
